import React, { memo, useState, Suspense, useEffect } from 'react'
import type { FC, ReactNode } from 'react'
import { Menu, ConfigProvider } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import type { MenuProps } from 'antd'
import { useNavigate, useLocation } from 'react-router-dom'
import { useRoutes } from 'react-router-dom'

import { resetAllStore } from '../../../store/index'
import { useMySelector, MyShallEqual, useMyDispatch } from '../../../store'

import styles from './index.module.scss'
import routes from '../../../router'

type MenuItem = Required<MenuProps>['items'][number]

interface IProps {
  children?: ReactNode
}

const items: MenuItem[] = [
  {
    label: '创建',
    key: 'create',
    icon: <PlusOutlined />
  },
  {
    label: '代码列表',
    key: 'code-list'
  },
  {
    label: '卡片分享',
    key: 'card-shared'
  }
]

const TarbarSelector: FC<IProps> = () => {
  const dispatch = useMyDispatch()
  const navigate = useNavigate()
  const location = useLocation()
  const { shareOrEdit } = useMySelector(
    (state) => ({
      shareOrEdit: state.success.shareOrEdit
    }),
    MyShallEqual
  )
  const [current, setCurrent] = useState('')

  useEffect(() => {
    switch (location.pathname) {
      case '/list':
        setCurrent('code-list')
        break
      case '/create':
        setCurrent('create')
        break
      case '/card-shared':
        setCurrent('card-shared')
        break
      default:
        setCurrent('create')
        break
    }
  }, [location.pathname])

  const onClick: MenuProps['onClick'] = (e) => {
    setCurrent(e.key)
    dispatch(resetAllStore())
    if (e.key === 'code-list') {
      navigate('/list')
      // window.location.reload()
    } else if (e.key === 'create') {
      navigate('/create')
    } else if (e.key === 'card-shared') {
      navigate('/card-shared')
    }
  }
  return (
    <div className={styles.container}>
      <ConfigProvider
        theme={{
          components: {
            Menu: {
              horizontalItemSelectedColor: '#00b96b'
            }
          }
        }}
      >
        <div className={styles.logo}>
          <div className={styles.h3}>Code Share</div>
        </div>
        <Menu
          onClick={onClick}
          selectedKeys={shareOrEdit ? [] : [current]}
          mode="horizontal"
          items={items}
          className={styles.menu}
        />
      </ConfigProvider>
      {/* <Routes>
        <Route path="/create" element={<Create />}></Route>
        <Route path="/success" element={<Successcreate />}></Route>
        <Route path="/" element={<Navigate to="/create" />} />
      </Routes> */}

      <Suspense fallback="">{useRoutes(routes)}</Suspense>
    </div>
  )
}

export default memo(TarbarSelector)
